<template>
  <el-row :gutter="20">
    <el-col :xs="24" :sm="8">
      <!-- 智能客服输入 -->
      <el-card tabindex="-1" class="box-card">
        <SpeechGeneration
          @onSubmitSave="onSubmitSave"
          :disabled="!radioValue.voice_id"
          :loading="radioValue.btloading"
        />
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="8">
      <!-- 训练数据 -->
      <el-card class="box-card">
        <SoundModelOptions @onRadioValue="onRadioValue" />
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="8">
      <el-card v-loading="state.speechAudioLoading" class="box-card">
        <FlexScroll ref="flexScroll" id="speechAudioList" @scroll="nextPage">
          <SpeechAudioList :soundHistoryList="state.soundHistoryList" />
        </FlexScroll>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { APITtsAdd } from "@/api/ApiSpeechModel"
import debounce from "@/utils/debounce"
import Speech from "@/utils/speech"
import message from "element-plus/es/components/message/index.mjs"
import { onMounted, reactive, ref } from "vue"
import SoundModelOptions from "./components/soundModelOptions.vue"
import SpeechAudioList from "./components/speechAudioList.vue"
import SpeechGeneration from "./components/speechGeneration.vue"
import FlexScroll from "@/components/FlexScroll/index.vue"

import useSpeechModel from "./useSpeechModel"

const { state, nextPage, soundHistory } = useSpeechModel()

const radioValue = reactive({
  voice_id: "",
  voice_name: "",
  btloading: false
})

const flexScroll = ref(null)

const toTop = () => {
  // @ts-ignore
  flexScroll.value && flexScroll.value.toTop()
}

onMounted(() => {
  Speech.instance.on("tts", (msg: any) => {
    console.log(msg)
    try {
      state.soundHistoryList.unshift({
        messages: msg.text,
        url: msg.url,
        id: Number(msg.id)
      })
      toTop()
    } catch {
      console.error()
    }
  })
  // 获取历史记录
  soundHistory()
})

// 保存
const onSubmitSave = debounce(async (e: string) => {
  radioValue.btloading = true
  const p_2 = {
    voice_id: radioValue.voice_id,
    messages: e
  }
  const { code } = await APITtsAdd(p_2)
  if (code === 200) {
    radioValue.btloading = false
    message.success("保存成功")
  }
}, 300)

// 模型id赋值
const onRadioValue = (e: any) => {
  radioValue.voice_id = e.id
  radioValue.voice_name = e.voice_name
}
</script>

<style lang="scss" scoped>
.box-card {
  height: calc(100vh - 120px);
  position: relative;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    width: 0;
  }
}

::v-deep .el-card__body {
  width: 100%;
  height: 100%;
}
</style>
